import struct


class DataUtils:
    """数据转换工具类"""

    @staticmethod
    def pack_register(address, value):
        """打包寄存器地址和值"""
        return struct.pack('>H', address) + struct.pack('>H', value)

    @staticmethod
    def unpack_registers(data):
        """解包寄存器值列表"""
        values = []
        for i in range(0, len(data), 2):
            if i + 1 < len(data):
                value = (data[i] << 8) | data[i + 1]
                values.append(value)
        return values

    @staticmethod
    def int_to_hex(value, digits=4):
        """整数转16进制字符串"""
        return f"0x{value:0{digits}X}"

    @staticmethod
    def hex_to_int(hex_str):
        """16进制字符串转整数"""
        try:
            return int(hex_str, 16)
        except ValueError:
            return 0

    @staticmethod
    def format_register_value(value, data_type):
        """根据数据类型格式化寄存器值"""
        if data_type == "int16":
            return value if value < 32768 else value - 65536
        elif data_type == "uint16":
            return value
        elif data_type == "int32":
            # 需要两个寄存器组合
            return value
        elif data_type == "uint32":
            return value
        elif data_type == "float":
            return struct.unpack('>f', struct.pack('>I', value))[0]
        else:
            return value